﻿using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;

namespace Huasky.Gm.Core;

public static class UtilExtension
{
    private static readonly JsonSerializerSettings _setting = new()
    {
        DateFormatString = "yyyy-MM-dd HH:mm:ss",
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };

    /// <summary>
    /// JSON序列化
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ToJson<T>(this T str) => JsonConvert.SerializeObject(str, _setting);

    /// <summary>
    /// JSON反序列化
    /// </summary>
    /// <typeparam name="T">序列化类型</typeparam>
    /// <param name="str">json字符串</param>
    /// <returns></returns>
    public static T ToObject<T>(this string str) => JsonConvert.DeserializeObject<T>(str, _setting);

    /// <summary>
    /// 复制对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static T Copy<T>(this T obj) => obj.ToJson().ToObject<T>();



}
